﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Identity;

namespace AdminManager.System
{
    [Dependency(ReplaceServices = true)]
    //
    [ExposeServices(typeof(IIdentityUserAppService), typeof(IdentityUserAppService), typeof(UserAppService),IncludeSelf =true)]
    [Authorize(IdentityPermissions.Users.Default)]
    public class UserAppService : IdentityUserAppService, ITransientDependency
    { 
        public UserAppService(IdentityUserManager userManager, 
            IIdentityUserRepository userRepository, 
            IIdentityRoleRepository roleRepository, 
            IOptions<IdentityOptions> identityOptions) : base(userManager, userRepository, roleRepository, identityOptions)
        {
            
        }
        [Authorize(IdentityPermissions.Users.Create)]
        public override async Task<IdentityUserDto> CreateAsync(IdentityUserCreateDto input)
        {
            IdentityUserDto identityUserDto = await base.CreateAsync(input);
            string deptId = input.GetProperty<string>(AdminManagerDtoExtensions.ExtIdentityUserCreateOrUpdateDtoOfDeptId);
            if (!deptId.IsNullOrWhiteSpace())
            {
               await UserManager.AddToOrganizationUnitAsync(identityUserDto.Id,Guid.Parse(deptId));
            }
            return identityUserDto;
        }
        [Authorize(IdentityPermissions.Users.Update)]
        public override async Task<IdentityUserDto> UpdateAsync(Guid id, IdentityUserUpdateDto input)
        {
            string deptId = input.GetProperty<string>(AdminManagerDtoExtensions.ExtIdentityUserCreateOrUpdateDtoOfDeptId);
            if (!deptId.IsNullOrWhiteSpace())
            {
                await UserManager.SetOrganizationUnitsAsync(id, Guid.Parse(deptId));
            }
            
            return await base.UpdateAsync(id, input);
        }
    }
}
